// 购物车状态
import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/cart.js'
const cart = {
  namespaced: true,
  state: () => ({
    cartList: [] // 购物车列表
  }),
  getters: {
    // 总价格
    allPrice (state) {
      return state.cartList.reduce((a, c) => a + c.count * c.price, 0)
    },
    // 总数量
    allCount (state) {
      return state.cartList.reduce((a, c) => a + c.count, 0)
    },
    // 已选择数量
    selectedCount (state) {
      return state.cartList.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
    },
    // 总价钱
    selectedPrice (state) {
      return state.cartList.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0)
    },
    // 全选-判断单选是否全选中
    isAll (state) {
      return state.cartList.every((item) => item.selected)
    }
  },
  mutations: {
    setCartList (state, list) {
      state.cartList = list
    },
    // 修改单选状态
    singleCheck (state, { skuId, selected }) {
      const item = state.cartList.find((item) => item.skuId === skuId)
      item.selected = selected
    }
  },
  actions: {
    // 加入购物车
    async asyncSetCartList (ctx, { skuId, count }) {
      // 调用购物车接口
      await insertCart({ skuId, count })
      // 获取购物车列表
      const res = await findCartList()
      ctx.commit('setCartList', res.result)
    },
    // 删除购物车
    async asyncDelCart (ctx, ids) {
      await deleteCart(ids)
      // 获取购物车列表
      const res = await findCartList()
      ctx.commit('setCartList', res.result)
    },
    // 单选购物车
    async asyncSingleCheck (ctx, goods) {
      // 1. 调用单选业务接口
      await updateCart(goods)
      // 2. 获取最新购物车列表接口
      const res = await findCartList()
      // 3. 把购物车列表存入state
      ctx.commit('setCartList', res.result)
    },
    // 全选
    async asyncAllCheck (ctx, selected) {
      await checkAllCart({
        selected,
        ids: ctx.state.cartList.map(item => item.skuId)
      })
      // 2. 获取最新购物车列表接口
      const res = await findCartList()
      // 3. 把购物车列表存入state
      ctx.commit('setCartList', res.result)
    },
    // 修改数量
    async asyncChangeCount (ctx, { good, count }) {
      // 1. 调用更新数量接口
      await updateCart({
        skuId: good.skuId,
        selected: good.selected,
        count
      })
      // 2. 获取最新购物车列表接口
      const res = await findCartList()
      // 3. 把购物车列表存入state
      ctx.commit('setCartList', res.result)
    }
  }
}

export default cart
